<template>
	<view class="container">
		<uni-nav-bar :title="category2Name" fixed statusBar :border="false" height="88rpx" left-icon="left" @clickLeft="onClickLeft"></uni-nav-bar>
		<scroll-view scroll-x class="scroll" :scroll-left="left" :scroll-with-animation="true" enhanced :show-scrollbar="false">
			<view class="item" :class="activeIndex == index ? 'active' : ''" v-for="(item, index) in categoryList" :key="item.id"
				@click="showThreeCategory(index)">
				<view class="txt u-ellipsis">{{ item.name }}</view>
			</view>
		</scroll-view>

		<scroll-view :style="{height:`calc(100vh - 168rpx - ${statusBarHeight}px)`}" style="overflow: hidden;" scroll-y enhanced :show-scrollbar="false" @scrolltolower="scrolltolower"
			:scroll-with-animation="true" refresher-enabled @refresherrefresh="pulldownRefresh" :refresher-triggered="refreshStatus" @touchmove.stop>
			<view class="list" v-if="goodsList.length > 0">
				<view class="item" v-for="(item,index) in goodsList" :key="item.id">
					<view class="pic">
						<image :src="item.storeImgUrl ? item.storeImgUrl:'/static/index/noneImg.png'" mode="aspectFill"></image>
						<view class="none" v-if="item.productState != '0'">
							<text v-if="item.productState == '1'">已停用</text>
							<text v-if="item.productState == '2'">已淘汰</text>
						</view>
					</view>
					<view class="info">
						<view class="title u-ellipsis">
							{{ item.commodityName }}
						</view>
						<view class="subtitle">
							<text>进价:{{ item.outboundPrice }}元</text>
							<text>零售价:{{ item.storePrice }}元</text>
							<text>毛利:{{ item.storePrice | subtract(item.outboundPrice) }}元</text>
							<text>库存:{{ item.stockNum }}</text>
							<text>销量:{{ item.salesNum }}</text>
							<text>期初库存:{{ item.initialInventory }}</text>
						</view>
						<view class="btn-list">
							<view class="btn type-1" @click="addProcure(item)" v-if="item.productState == '0' && item.isPick == '1'">点采</view>
							<view class="btn type-1" @click.stop="updatePrice(item)">修改售价</view>
							<view class="btn type-1" @click.stop="()=> {$navTo('./goodsDetail',{id:item.id});newPage = '0';}">详情</view>
						</view>
					</view>
				</view>
			</view>
			<uni-load-more :status="loading" v-if="goodsList.length > 0"></uni-load-more>
			<view style="width: 100%;height: 100%;background-color: #f7f7f7;display: flex;justify-content: center;align-items: center;"
				v-if="goodsList.length == 0">
				<image src="../../static/index/nonedata.png" mode="aspectFill" style="width: 400rpx;height: 400rpx;"></image>
			</view>
		</scroll-view>
		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="修改售价" @confirm="submit" @close="close" before-close>
				<template>
					<uni-forms ref="form" :model="formData" :rules="rules" label-width="50" validate-trigger="blur">
						<uni-forms-item label="售价:" name="storePrice">
							<uni-easyinput type="number" v-model="formData.storePrice" placeholder="请输入售价" :clearable="false" trim="all" adjust-position />
						</uni-forms-item>
					</uni-forms>
				</template>
			</uni-popup-dialog>
		</uni-popup>
		<cls-DragBtn is-dock  :bottom-px="250" @btnClick="dianCaiclick">
			<view class="floatBox btn type-1">点采</view>
		</cls-DragBtn>
	</view>
</template>

<script>
	var screenWidth = uni.getSystemInfoSync().windowWidth;
	let itemWidth = screenWidth / 5; //表示窗口横排显示5个item=
	import { DecimalUtils } from '../../utils/math';
	import { reqGoodsByCategory, reqCategoryTree, reqUpdatePrice,reqAddPurchase } from '@/apis/goods.js';
	export default {
		name:"ThreeCategory",
		data() {
			return {
				category2Name:'', // 二级分类名称
				newPage: "0",
				activeIndex: 0,
				categoryList: [],
				left: 0,
				categoryId3: '',
				categoryId2: '',
				categoryId1: '',
				page: {
					pageNum: 1,
					pageSize: 15,
					total: 0,
				},
				goodsList: [],
				allCategoryList: [],
				refreshStatus: false, // 下拉刷新开关
				loading: 'loading',
				// 表单数据
				formData: {
					storePrice: null,
					id: '',
				},
				rules: {
					// 对name字段进行必填验证
					storePrice: {
						rules: [{
								required: true,
								errorMessage: '请输入售价',
							},
							{
								format: 'number',
								errorMessage: '售价格式错误'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									let reg = /^(?!(^0$|0\.0{1,2}$))[0-9]+(\.[0-9]{1,2})?$/
									if (!reg.test(value)) {
										callback('售价最多两位小数')
									}
								}
							}
						],
					}
				},
			}
		},
		filters: {
			subtract(value, params) {
				return DecimalUtils.subtract(value, params);
			}
		},
		async onLoad(params) {
			this.categoryId3 = params?.categoryId3;
			// 二级分类
			this.categoryId2 = params?.categoryId2;
			this.categoryId1 = params?.categoryId1;
			await this.getCategoryEasyList();
			// this.getGoodsList();
		},
		onShow() {
			if (this.newPage == "1") this.refreshPage();
			this.newPage = "0";
		},
		methods: {
			async getGoodsList(isAll) {
				let level = 3;
				if (isAll) level = 2;
				let { categoryId3: categoryId, page: { pageNum, pageSize } } = this;
				let res = await reqGoodsByCategory({ categoryId, pageNum, pageSize, categoryLevel: level, filter: 0 });
				if (res.code === 200) {
					const data = res.data;
					let arr = [...this.goodsList, ...data.list];
					const map = new Map();
					const newArr = arr.filter(v => !map.has(v.id) && map.set(v.id, v));
					this.goodsList = newArr;
					console.log(this.goodsList);
					if (res.data.isLastPage) {
						this.loading = "noMore";
					}
					this.refreshStatus = false;
				}
			},
			async getCategoryEasyList() {
				let res = await reqCategoryTree();
				if (res.code === 200) {
					this.allCategoryList = res.data.categoryList;
					let { categoryId1, categoryId2 } = this;
					const categoryObj1 = this.allCategoryList.find(item => item.id === categoryId1);
					const categoryArr1 = categoryObj1.children;
					const categoryObj2 = categoryArr1.find(item => item.id === categoryId2)
					const categoryArr2 = categoryObj2.children;
					categoryArr2.unshift({ id: categoryId2, name: "全部" })
					this.categoryList = categoryArr2;
					this.category2Name = categoryObj2.name;
					let index = this.categoryList.findIndex(item => item.id == this.categoryId3);
					this.showThreeCategory(index);
				}
			},
			showThreeCategory(index) {
				if (index === this.activeIndex) return;
				this.goodsList = [];
				this.loading = "loading";
				this.page = {
					pageNum: 1,
					pageSize: 15,
				};
				this.categoryId3 = this.categoryList[index].id;
				if (index == 0) {
					this.getGoodsList(true);
				} else {
					this.getGoodsList(false);
				}
				this.activeIndex = index;
				this.$nextTick(() => {
					setTimeout(() => {
						this.scrollLeft();
					}, 0)
				})
			},
			//点击item时调用scrollLeft方法
			scrollLeft() {
				let tabList = this.categoryList;
				let tabIndex = this.activeIndex;
				let scrollX = itemWidth * tabIndex - itemWidth * 2;
				let maxScrollX = (tabList.length + 1) * itemWidth;
				if (scrollX < 0) {
					scrollX = 0;
				} else if (scrollX >= maxScrollX) {
					scrollX = maxScrollX;
				}
				this.left = scrollX;
			},
			scrolltolower() {
				console.log("滚动到底部");
				if (this.loading == "noMore") {
					return;
				}
				this.page.pageNum++;
				this.loading = "loading";
				if (this.activeIndex == 0) {
					this.getGoodsList(true);
				} else {
					this.getGoodsList(false)
				}
			},
			pulldownRefresh() {
				console.log('下拉刷新');
				this.refreshStatus = true;
				this.page = {
					pageNum: 1,
					pageSize: 15
				};
				this.goodsList = [];
				this.loading = "loading";
				if (this.activeIndex == 0) {
					this.getGoodsList(true);
				} else {
					this.getGoodsList(false)
				}
			},
			updatePrice(item) {
				const firstCode = item.firstCode;
				const specificationList = item.specificationList;
				console.log(specificationList.length);
				if (specificationList.length === 1) {
					this.formData = {
						id: specificationList[0].id,
						storePrice: specificationList[0].storePrice
					}
					this.$refs.inputDialog.open();
				} else {
					this.newPage = "1";
					this.$navTo('./changePrice', { commodityId: item.commodityId });
				}
			},
			submit() {
				this.$refs.form.validate().then(async (suc) => {
					let res = await reqUpdatePrice({ ...this.formData });
					if (res.code === 200) {
						this.$refs.inputDialog.close();
						uni.utils.toast('修改成功', 'success')
						this.page = {
							pageNum: 1,
							pageSize: 15
						};
						this.goodsList = [];
						this.loading = "loading";
						if (this.activeIndex == 0) {
							this.getGoodsList(true);
						} else {
							this.getGoodsList(false)
						}
					}
				}).catch((err) => {
					console.log('失败')
				})
			},
			close() {
				this.formData = {
					id: '',
					storePrice: null
				};
				this.$refs.inputDialog.close();
				console.log("关闭");
			},
			refreshPage() {
				this.page = {
					pageNum: 1,
					pageSize: 15
				};
				this.goodsList = [];
				this.loading = "loading";
				if (this.activeIndex == 0) {
					this.getGoodsList(true);
				} else {
					this.getGoodsList(false)
				}
			},
			dianCaiclick() {
				this.$navTo('/pages/procure/waitSubmit')
			},
			async addProcure(item) {
				let commodityId = item.commodityId;
				let res = await reqAddPurchase({commodityId});
				if(res.code === 200) {
					uni.utils.toast('添加点采成功', 'success');
				}
			}
		},
	}
</script>
<style>
	.popup-success {
		color: #fff;
		background-color: #e1f3d8;
		z-index: 2000;
	}
</style>
<style scoped lang="scss">
	.container {
		display: flex;
		height: 100vh;
		flex-direction: column;
	}

	.scroll {
		position: sticky;
		top: 0;
		left: 0;
		z-index: 1000;
		width: 100%;
		box-sizing: border-box;
		white-space: nowrap;
		background-color: #f6f6f6;

		.item {
			display: inline-block;
			text-align: center;
			width: 20%;
			padding: 0 5rpx;
			box-sizing: border-box;

			&.active {
				.txt {
					color: $uni-main-bgColor;
				}

				border-bottom: 2px solid $uni-main-bgColor;
			}

			.txt {
				font-weight: 400;
				font-size: $uni-font-size-unBase;
				height: 80rpx;
				box-sizing: border-box;
				width: 100%;
				line-height: 80rpx;
				color: #333333;
				display: inline-block;
				text-align: center;
			}
		}
	}

	.list {
		padding: 0 15rpx;
		// flex: 1;
		// overflow: hidden;
		.item {
			display: flex;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #ccc;

			.pic {
				width: 240rpx;
				height: 240rpx;
				background-color: #f7f7f7;
				position: relative;
				.none {
					top: 0;
					left: 0;
					position: absolute;
					width: 240rpx;
					height: 240rpx;
					background: rgba(0, 0, 0, 0.6);
					border-radius: 10rpx;
					line-height: 240rpx;
					color: #fff;
					text-align: center;
					font-weight: bold;
					font-size: 34rpx;
				}
				image {
					width: 100%;
					height: 100%;
				}
			}

			.info {
				padding-left: 20rpx;
				flex: 1;
				min-width: 440rpx;
				display: flex;
				flex-direction: column;

				.title {
					width: 100%;
					margin-bottom: 5rpx;
					font-size: $uni-font-size-upBase;
					color: #000;
				}

				.subtitle {
					display: flex;
					flex-wrap: wrap;

					text {
						font-size: $uni-font-size-mini;
						width: 50%;
						color: #333;
						margin-bottom: 5rpx;
					}
				}

				.btn-list {
					margin-top: auto;
					display: flex;
					justify-content: flex-end;
					.btn {
						width: 120rpx;
						font-size: $uni-font-size-small;
						text-align: center;
						margin-right: 30rpx;
						border-radius: 5rpx;
						height: 60rpx;
						box-sizing: border-box;
						line-height: 60rpx;
					}
				}
			}
		}
	}

	.floatBox {
		// position: fixed;
		// bottom: 150rpx;
		// right: 50rpx;
		width: 100rpx;
		height: 100rpx;
		line-height: 100rpx !important;
		box-shadow: 0 1px 5px 2px rgba(0, 0, 0, .3);
		font-weight: 600;
		text-align: center;
		border-radius: 50%;
		padding: 10rpx;
		box-sizing: border-box;
	}
</style>